import React, { Component } from 'react'
import { Menu, Modal, message, Dropdown, Icon } from 'antd';
import u from '../../../common.js'
import '../../../static/routineMonitoring/collectionPoint.less'
import { Array } from 'core-js';


const { SubMenu } = Menu;
const { BMap, BMAP_STATUS_SUCCESS } = window
let map, circlearr = [], markerAll = [];
class CollectionPoint extends Component {
  constructor(props) {
    super(props)
    this.state = {
      mode: 'inline',
      theme: 'light',
      flag: true,
      flag2: true,
      historyList: [],
      num: 0,
      distance: 3,
      weararr: [],
      visible: false,
      id: 0,
      index: null,
      caijiudate: [],
      userId: localStorage.getItem("userId"),
      disList: [1, 2, 3, 4, 5],
      markerAll: [],
      content: '',
      title: '',
      point: '',
      iscanadd: localStorage.getItem("iscanadd") == 'false' ? false : true
    }
  }

  componentDidMount() {
    // 获取历史记录
    this.onGetHistory() //渲染

    // this.onClickMap()
  }
  serchgps() {  //百度地图api搜索纯复制
    // 百度地图API功能
    function G(id) {
      return document.getElementById(id);
    }

    // map.centerAndZoom("北京",12);                   // 初始化地图,设置城市和地图级别。

    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
      {
        "input": "suggestId"
        , "location": map
      });

    ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
      var str = "";
      var _value = e.fromitem.value;
      var value = "";
      if (e.fromitem.index > -1) {
        value = _value.province + _value.city + _value.district + _value.street + _value.business;
      }
      str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

      value = "";
      if (e.toitem.index > -1) {
        _value = e.toitem.value;
        value = _value.province + _value.city + _value.district + _value.street + _value.business;
      }
      str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
      G("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
      var _value = e.item.value;
      myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
      G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

      setPlace();
    });

    function setPlace() {
      // map.clearOverlays();    //清除地图上所有覆盖物
      function myFun() {
        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
        map.centerAndZoom(pp, 18);
        // map.addOverlay(new BMap.Marker(pp));    //添加标注
      }
      var local = new BMap.LocalSearch(map, { //智能搜索
        onSearchComplete: myFun
      });
      local.search(myValue);
    }
  }

  onGetHistory() {
    u.findPosition({ uid: localStorage.getItem("userId") }, data => {
      // console.log(data)
      // if(true){
      //   return
      // }
      markerAll = []
      data.PositionList.forEach((el, index) => {
        data.PositionList[index].index = index + 1
      })
      this.setState((props, prevState) => ({
        historyList: data.PositionList,
        distance: data.PositionList[0].distance
      }), () => {
        this.onClickMap()
        this.wear(data.PositionList[0].id)
        this.serchgps()
      })
    })
  }

  onCaiDianList(index, id, distance, e) {
    if (e.target.className == 'closeimg') {
      return
    }
    this.setState((props, prevState) => ({
      num: index,
      distance: distance
    }), () => {
      this.mapfocus()
      map.centerAndZoom(markerAll[index].point, 12);
    })
    this.wear(id)
  }
  wear(id) {
    u.morePostion({ p_id: id }, data => {
      this.setState((props, prevState) => ({
        weararr: data.roundList
      }))
    })
  }
  mapfocus(point) { //绘制圆形范围
    let allOverlay = markerAll || map.getOverlays();
    map.removeOverlay(circlearr[0]);
    var circle = new BMap.Circle(point || allOverlay[this.state.num].point, allOverlay[this.state.num].distance * 1000, {
      fillColor: allOverlay[this.state.num].isCollect ? "red" : "blue",
      strokeWeight: 1,
      fillOpacity: allOverlay[this.state.num].isCollect ? 0.1 : 0.2,
      strokeOpacity: 0.3
    });
    circlearr[0] = circle;
    map.addOverlay(circle);
  }
  addMarker(point, index, isCollect, distance) {  //绘制所有的点
    let that = this;
    let src = isCollect ? require("../../../static/image/reda.png") : require("../../../static/image/lan.png")
    let label = new BMap.Label(index, { offset: index > 10 ? new BMap.Size(2, 3) : new BMap.Size(4, 3) });
    let myIcon = new BMap.Icon(src, new BMap.Size(35, 35));
    let marker = new BMap.Marker(point, {
      icon: myIcon
    }, label);
    map.addOverlay(marker);
    marker.setLabel(label);
    marker.index = index
    marker.distance = distance
    marker.isCollect = isCollect
    if (isCollect) {
      marker.enableDragging()
    }
    marker.addEventListener("dragstart", start);

    // marker.addEventListener("dragleave", over);
    // function over(){
    //   console.log(111)
    // }
    function start() {
      let p = marker.getPosition()
      that.setState((props, prevState) => ({
        num: marker.index - 1,
        distance: that.state.num == marker.index - 1 ? that.state.distance : marker.distance
      }), () => {
        that.mapfocus(p)
      });

    }
    marker.addEventListener("dragend", attribute);
    function attribute() {
      let [p, index, address] = [marker.getPosition(), marker.index, null];
      markerAll[marker.index - 1].point = p
      var geoc = new BMap.Geocoder();
      geoc.getLocation(p, function (rs) {
        let addComp = rs.addressComponents;
        address = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber
        let [arr, caijiudate, obj] = [[], that.state.caijiudate.slice(0), {
          lng: p.lng,
          lat: p.lat,
          index: marker.index,
          address: address,
        }];

        caijiudate.length && caijiudate.some((el, index) => {
          if (el.index == obj.index) {
            caijiudate[index] = obj
            return true
          }
        }) ? "" : caijiudate.push(obj);
        that.setState((props, prevState) => ({
          caijiudate: caijiudate,
          num: marker.index - 1
        }), () => {
          that.mapfocus(p)
        });
        // console.log("marker的位置是" + p.lng + "," + p.lat);
      })
    }
    markerAll.push(marker)
    // that.setState((props,prevState)=>({
    //   marker
    // }))
  }
  onClickMap() {  //添加采集点的绘制
    map = new BMap.Map("allmap");

    map.setMapStyle({ styleJson: u.stylejson });
    var point = new BMap.Point(91.121398, 29.65004);
    map.centerAndZoom(point, 12);
    // 开启缩放
    map.setDefaultCursor("pointer");
    map.enableScrollWheelZoom(true);
    let that = this
    this.state.historyList.forEach((el, index) => {
      var pointt = new BMap.Point(el.longitude, el.latitude);
      that.addMarker(pointt, el.index, el.isCollect, el.distance);
    })
    this.mapfocus()
    var geoc = new BMap.Geocoder();
    function showInfo(e) {
      // if (that.state.num > 5) {
      //     setTimeout(() => {
      //         map.clearOverlays()
      //     }, 2000)
      //     return
      // }
      that.setState((props, prevState) => ({
        title: '添加采集点',
        content: "",
        point: e.point,
        visible: true,
      }))
      let geoc = new BMap.Geocoder();
      geoc.getLocation(e.point, function (rs) {
        var addComp = rs.addressComponents;
        let address = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber
        that.setState((props, prevState) => ({
          address: address,
          content: "当前位置：" + address.replace(/,/g, '') + '(经度：' + e.point.lng + "-纬度:" + e.point.lat + ')'
        }))

      })
    };
    map.addEventListener("click", showInfo);
  }

  handleMenuClick = (e) => {
    this.setState(prevState => ({
      distance: e.key || this.state.distance
    }), () => {
      markerAll[this.state.num].distance = this.state.distance
      this.mapfocus()
    });
  }
  onUpDown() {
    this.setState({
      flag: !this.state.flag
    })
  }
  add() {  //添加采集点
    this.addMarker(this.state.point, this.state.historyList.length + 1, true, this.state.distance); //绘制
    u.diTu({  //接口
      "id": 14,
      "longitude": this.state.point.lng,
      "latitude": this.state.point.lat,
      "distance": this.state.distance,
      'isPost': 0,
      'address': this.state.address,
      uid: this.state.userId,
      collect_name: localStorage.getItem('name')
    }, data => {
      message.success('打点成功', [1], )
      // localStorage.setItem("iscanadd", false)
      // this.setState((props, prevState) => ({
      //   iscanadd: false
      // }))
      this.onGetHistory() //重新渲染
    })

  }
  onUpDown2() {
    this.setState({
      flag2: !this.state.flag2
    })
  }
  delete() {   //删除一个采集点
    u.deletecaji({ id: this.state.id, uid: this.state.userId }, data => {
      this.onGetHistory()
      message.success('删除成功', [1], )
      let arr = this.state.historyList.slice(0)
      arr.splice(this.state.index, 1)

      this.setState((props, prevState) => ({
        historyList: arr,
      }))
    })
  }
  handleOk = (e) => { //点击ok
    switch (this.state.title) {
      case '删除':
        this.delete()
        break;
      case '添加采集点':
        // this.state.iscanadd ?
        //   this.add() : message.success('同一用户只能打一个点', [1], )
        this.add()
        break;
    }
    this.setState((props, prevState) => ({
      visible: false,
    }))
  }
  handleCancel = (e) => { //点击cancle
    this.setState({
      visible: false,
    });
  }
  clearMap(inde, index) {  //点击取消点返回原位
    this.setState((props, prevState) => ({
      distance: this.state.historyList[this.state.num].distance,
    }))
    let [allOverlay, el] = [map.getOverlays(), this.state.historyList[inde - 1]]
    allOverlay.some((item, index) => {
      if (item.index == inde) {
        map.removeOverlay(allOverlay[index])
      }
    })
    let pointt = new BMap.Point(el.longitude, el.latitude);
    this.addMarker(pointt, inde, el.isCollect, this.state.distance);
    this.reset(index)
    this.resetmakerall(index)
    this.state.num == this.state.caijiudate[index].index - 1 ? this.mapfocus() : ''
  }
  cjudate(d, index) {  //修改点的位置                                                    
    let obj = {
      longitude: d.lng,
      latitude: d.lat,
      //distance: this.state.distance,
      uid: this.state.userId,
      address: d.address
    }
    this.state.historyList.some((el, index) => {
      if (el.index == d.index) {
        obj.isPost = el.isPost
        obj.wxId = el.wxId
        obj.id = el.id
        obj.updateTime = el.updateTime
        obj.distance = markerAll[index].distance
      }
    })
    u.updatecaiji(obj, data => {
      message.success('修改成功', [1], )
      this.reset(index)
      this.onGetHistory()
    })
  }
  reset(index) {  //重置
    let arr = this.state.caijiudate.slice(0);
    arr.splice(index, 1);
    this.setState((props, prevState) => ({
      caijiudate: arr
    }))
  }
  resetmakerall(inx) {//重置
    this.state.historyList.some((el, index) => {
      if (this.state.caijiudate[inx].index == el.index) {
        markerAll[index].point.lat = el.latitude;
        markerAll[index].point.lng = el.longitude
        markerAll[index].distance = el.distance
      }
    })
  }
  render() {
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        {
          this.state.disList.map((item, index) => {
            return (
              <Menu.Item key={item}>{item}公里内</Menu.Item>
            )
          })
        }
      </Menu>
    )
    return (
      <div className='CollectionPoint'>
        {/* <Modal
          title={this.state.title}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          style={{ top: '50%', height: '300px', width: '600px' }}
          cancelText={'取消'}
          okText={'确认'}
        // bodyStyle={{height:'300px',width:'600px'}}
        >
          <p>{this.state.content}</p>
        </Modal> */}
        <div className='pop_shadow' style={{display:this.state.visible?"block":"none"}}>
          <div className='pop_shadow_son' >
            <div className='pop_shadow_header'>
              <p>添加采集点</p>
              <img src={require("../../../static/image/cloossee.png")} alt="" onClick={this.handleCancel.bind(this)}/>
            </div>
            <div className='pop_shadow_moddle'>
              {this.state.content}
            </div>
            <div className='pop_shadow_footer' >
              <button onClick={this.handleCancel.bind(this)}>取消</button>
              <button onClick={this.handleOk.bind(this)}>确定</button>
            </div>
          </div>
        </div>
        <div className='CollectionPoint_left'>
          <div onClick={this.onUpDown2.bind(this)} className='box2Title'>
            <span>附近的人（{this.state.weararr.length}）</span><img src={require('../../../static/image/jiantou.png')} className={this.state.flag2 ? 'imgtoggle' : ''} />
          </div>
          <div className={this.state.flag2 ? 'boxStyle boxStyleactive2' : 'boxStyle'}>
            {
              this.state.weararr.map((item, index) => {
                return (
                  <div className='boxList' key={index} onClick={() => {


                    const w = window.open('about:blank');
                    w.location.href = u.testurl + '/weixinqun/friendqun?id=' + item.id + '&name=' + item.user_name
                    localStorage.setItem("weixinkey", 1)
                    //window.location.reload()
                    // this.props.history.push({ pathname: "/weixinqun/friendqun", state: { id: item.id, name: item.user_name } });
                  }}>
                    <div className='boxListImg'>
                      <img src={require('../../../static/image/cjdefaule.png')} />
                    </div>
                    <div className='boxListContent'>
                      <div className='boxListTop'>{item.user_name || '匿名'}</div>
                      <div className='boxListBottom'>{item.signature}</div>
                    </div>
                  </div>
                )
              }
              )
            }
          </div>
        </div>

        <div className='CollectionPoint_middle'>
          <div id="allmap" className='map' style={{ height: '100%' }} onClick={this.showModal}></div>
          <div className="kilometreleft">
            <div id="r-result"><input type="text" id="suggestId" size="20" placeholder='搜索位置...' style={{ width: '360px', height: '39px', border: '1px solid rgb(82, 134, 255)', borderRadius: '2px', paddingLeft: '30px' }} />
              <img src={require('../../../static/image/seacrchh.png')} alt="" />
            </div>
            <div id="searchResultPanel" style={{ border: '1px solid rgb(82, 134, 255)', width: '360px', height: 'auto', display: 'none' }}></div>
          </div>
          <div className="kilometre">
            <Dropdown overlay={menu} trigger={['click']} onClick={this.handleMenuClick}>
              <a className="ant-dropdown-link" href="javaScript: void(0);" style={{ padding: '8px', color: '#5286ff', border: '1px solid #5286ff', display: 'inline-block', fontSize: '14px' }}>
                采集点范围：{this.state.distance}km &nbsp;&nbsp;<Icon type="down" />
              </a>
            </Dropdown>
          </div>
          <ul className='where'>
            {
              this.state.caijiudate && this.state.caijiudate.map((item, index) => {
                return (<li key={index}>
                  <span>采集点{item.index}位置：{item.address && item.address.replace(/,/g, '')}（{item.lat},{item.lng}）</span>
                  <button onClick={() => {
                    this.cjudate(item, index)
                  }}>确定</button>
                  <button onClick={() => {
                    this.clearMap(item.index, index)
                  }}>取消</button>
                </li>)
              })
            }
          </ul>
        </div>

        <div className='CollectionPoint_right'>
          <div className='caijiDian'>采集点</div>
          <div className='caijiDianBox'>
            {
              this.state.historyList.map((item, index) => {
                return (
                  <div className={[this.state.num === index ? 'caijiBox caijiActive' : (item.isCollect ? "caijiBox caijiActiveTwo" : 'caijiBox')]} onClick={this.onCaiDianList.bind(this, index, item.id, item.distance)} key={index}>
                    <div className='caijiOne'><span>采集点{index + 1}</span><span>{item.create_time}</span>{item.isCollect && <span style={{ lineHeight: '1' }}>    <img className='closeimg' onClick={(e) => {
                      e.stopPropagation()
                      this.setState((props, prevState) => ({
                        visible: true,
                        index: index,
                        id: item.id,
                        title: '删除',
                        content: "是否确定删除"
                      }))
                    }} src={require('../../../static/image/delete.png')} align='top' /></span>}</div>
                    <div className='caijiTwo'>{item.address}</div>
                    <div className='caijiThree' style={{ display: "flex", justifyContent: 'space-between' }}><span>{item.collect_name}</span><span>最后采集时间:2019.01.18 14:30:00</span></div>
                    <div className='caijiFour'><span>{item.longitude},{item.latitude}</span><span>{'<' + item.distance + 'km'}</span></div>
                  </div>
                )
              })
            }
          </div>
        </div>
      </div>
    )
  }
}

export default CollectionPoint